<?php
class child_c2_task_model
{		
	static public $program_type = array(
		'0' => '1000',//电影
		'1' => '1300',//电视剧
		'2' => '1107',//综艺
		'3' => '1001',//动漫
		'4' => '1108',//音乐
		'5' => '1002',//
		'6' => '1005',//教育
		'7' => '1103',//体育
		'8' => '1006',//生活
		'9' => '1102',//财经
		'12' => '1200',//广告
		'13' => '1101',//新闻
	);
	static public $file_mapping = array(
		'1.5' => '2',//标清0：原始码流 1: 400k 2: 700K 3: 1.3M  4: 2M 5: 2.3M 6：4M 7：6M 8: 8M 
		//9：10M 10：12M 11：14M 12：16M 13：18M 14：20M 15：22M 16：24M
		'2.5' => '2$3',//标清
		'8' => '2$3$5$6',//高清
		'2.3' => '2$3$5',//高清
		'4' => '2$3$5$6',//高清
		'15' => '',//4K
	);
	/**
	 * 获取图片FTP、http地址
	 * @param 图片路径 $img_path
	 * @param SPid $sp_id
	 */
	static public function get_image_url($img_path,$sp_id)
	{
		include_once dirname(dirname(dirname(__FILE__))).'/'.$sp_id.'/define.php';
		if(defined('HW_DOANLOAD_IMG_METHOD') && HW_DOANLOAD_IMG_METHOD=='ftp' && !empty($img_path))
		{
			$img_path = strrchr($img_path,'/');
			$img_url = HW_DOANLOAD_IMG_FTP.$img_path;
		}
		else
		{
			$img_url = nl_image::epg_video_image_url($img_path);
		}
		return $img_url;
	}
	/**
	 * 获取任务名称
	 */	
	static public function get_task_name($task_id)
	{
		$db = nn_get_db(NL_DB_READ);
		$sql = "select nns_name from nns_mgtvbk_c2_task where nns_id='$task_id'";
		return nl_db_get_col($sql, $db);
	}

	/**
	 * 添加连续剧
	 */
	static public function add_series($vod_info,$sp_id)
	{
		$action = 'REGIST';
		return self::do_series($vod_info,$action,$sp_id);
	}
	/**
	 * 修改连续剧
	 */
	static public function update_series($vod_info,$sp_id)
	{
		$action = 'UPDATE';
		return self::do_series($vod_info,$action,$sp_id);
	}
	/**
	 * 连续剧剧头注入
	 * @param $vod_info 连续剧信息
	 * @param $action 操作
	 * @param $sp_id SPID
	 */
	static public function do_series($vod_info,$action,$sp_id)
	{
		//$vod_info 中包含vod信息，任务ID，任务名称
		$vod_id = $vod_info['nns_id'];
        $program_id = $vod_id;
        include_once dirname(dirname(__FILE__)).'/define.php';		
		if(empty($vod_info['nns_task_name']))
		{
			$vod_info['nns_task_name'] = self::get_task_name($vod_info['nns_task_id']);
		}		
		if(empty($vod_info['nns_name']))
		{
			$vod_info['nns_name'] = $vod_info['nns_task_name'];
		}
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';	
		$sp_config = sp_model::get_sp_config($sp_id);
		$video_info = video_model::get_vod_info($program_id);
		if(isset($sp_config['import_id_mode']) && strlen($sp_config['import_id_mode']) > 0 && (int)$sp_config['import_id_mode'] > 0)
		{
			//$video_info = video_model::get_vod_info($program_id);
			switch ($sp_config['import_id_mode']) 
			{				
				case '1':					
					$vod_id = '000000'.$video_info['nns_integer_id'];
					$vod_id = str_pad($vod_id,32,"0");
					break;
				case '2':
					$vod_id = $video_info['nns_asset_import_id'];
					break;
				case '3':
					$vod_id = CSP_ID.'000'.$video_info['nns_integer_id'];
					$vod_id = str_pad($vod_id,32,"0");
					break;
			}			
		}
		
		$xml_str .= '<Object ElementType="Series" ContentID="' .$vod_id. '" Action="' . $action . '">';		
		$xml_str .= '<Property Name="Name">'.htmlspecialchars($vod_info['nns_name'],ENT_QUOTES).'</Property>';
		$xml_str .= '<Property Name="LicensingWindowStart">'. date('YmdHis').'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
		$xml_str .= '<Property Name="LicensingWindowEnd">'. date('YmdHis',time()+ 3*365*24*60*60).'</Property>';//有效结束时间(YYYYMMDDHH24MiSS)			
		$xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
		$xml_str .= '<Property Name="OriginalName">'.htmlspecialchars($vod_info['nns_alias_name'],ENT_QUOTES).'</Property>';//原名
		if(empty($vod_info['nns_eng_name']))
		{
			$vod_info['nns_eng_name'] = date('YmdHis');
		}
		$xml_str .= '<Property Name="SortName">'.htmlspecialchars($vod_info['nns_eng_name'],ENT_QUOTES).'</Property>';//索引名称供界面排序
		$xml_str .= '<Property Name="SearchName">'.$vod_info['nns_pinyin'].'</Property>';//搜索名称供界面搜索
		$xml_str .= '<Property Name="OrgAirDate">' . date('Ymd',strtotime($vod_info['nns_show_time'])).'</Property>';//首播日期(YYYYMMDD)
		$xml_str .= '<Property Name="CPContentID"></Property>';//CP 内部对于该对象的唯一标识，全局唯一标识
		$xml_str .= '<Property Name="DisplayAsNew"></Property>';//新到天数
		$xml_str .= '<Property Name="DisplayAsLastChance">300</Property>';//剩余天数
		$xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护    1:有拷贝保护
		$xml_str .= '<Property Name="Price"></Property>';//含税定价
		$xml_str .= '<Property Name="VolumnCount">'.$vod_info['nns_all_index'].'</Property>';//总集数
		$xml_str .= '<Property Name="Status">1</Property>';//状态标志,0:失效 1:生效
		$nns_summary = mb_strcut($vod_info['nns_summary'], 0,1024,'utf-8');
		$xml_str .= '<Property Name="Description">'.htmlspecialchars($nns_summary,ENT_QUOTES).'</Property>';//描述信息
		$xml_str .= '<Property Name="ContentProvider">'.$vod_info['nns_import_source'].'</Property>';//节目提供商
		$keyword = str_replace(array('|',' ','/'), ',', $vod_info['nns_keyword']);
		$keyword = mb_strcut($keyword, 0,256,'utf-8');
		$xml_str .= '<Property Name="KeyWords">'.htmlspecialchars($keyword,ENT_QUOTES).'</Property>';//关键字
		if(empty($vod_info['nns_kind']))
		{
			$vod_info['nns_kind'] = $vod_info['nns_keyword'];
		}
		$tags = str_replace(array('|',' ','/'), ',', $vod_info['nns_kind']);
		$tags = mb_strcut($tags, 0,256,'utf-8');
		$xml_str .= '<Property Name="Tags">'.$tags.'</Property>';//关联标签
		$xml_str .= '<Property Name="ViewPoint"></Property>';//看点,非常简短的剧情描述
		$xml_str .= '<Property Name="StarLevel">5</Property>';//推荐星级 
		$xml_str .= '<Property Name="Rating"></Property>';//限制类别 采用国际通用的 Rating 等级 
		$xml_str .= '<Property Name="Awards"></Property>';//所含奖项 多个奖项之间使用；分隔

        //修改说明：爱上悦me同步CP信息新增下发【内容提供商ID】
        //修改人员：kan.yang@starcor.com
        //修改时间：2018-05-14 14:36:00
        $arr_cntv_cp_relation = get_config_v2('g_cntv_me_cp_relation');
        if((!isset($arr_cntv_cp_relation) || empty($arr_cntv_cp_relation)) && isset(self::$arr_cp_relation))
        {
            $arr_cntv_cp_relation = self::$arr_cp_relation;
        }
        if(isset($arr_cntv_cp_relation) && !empty($arr_cntv_cp_relation))
        {
            $str_producer = isset($vod_info['nns_producer']) && strlen($vod_info['nns_producer']) > 0 ? $vod_info['nns_producer'] : '';
            if(isset($arr_cntv_cp_relation[$vod_info['nns_producer']]))
            {
                $str_producer = $arr_cntv_cp_relation[$vod_info['nns_producer']];
            }
            elseif(isset($arr_cntv_cp_relation['default']))
            {//如果上游cpid为空，或者不在对照表里，就传递一个默认值

                $str_producer = $arr_cntv_cp_relation['default'];
            }
            $xml_str .= '<Property Name="Reserve1">' . $str_producer . '</Property>';//保留字段
        }
        else
        {
            $xml_str .= '<Property Name="Reserve1"></Property>';//保留字段
        }
		$xml_str .= '<Property Name="Reserve2"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve3"></Property>';//保留字段
		$xml_str .= '<Property Name="UniContentId"></Property>';//关联内容唯一标识								
		$xml_str .= '</Object>';
		$pic_id = '';
		if(empty($vod_info['nns_image2']) && !empty($vod_info['nns_image_v']))
		{
			$vod_info['nns_image2'] = $vod_info['nns_image_v'];
		}
		if(!empty($vod_info['nns_image2']))
		{
			$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
			$pic_id = CSP_ID . self::get_image_id($img_save_name);
			$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
			if(file_exists($file_img))
			{										 
				$pic_url = self::get_image_url($img_save_name,$sp_id);
				$xml_str .= '<Object ElementType="Picture" pictureId="' .$pic_id. '" Action="' . $action . '">';
				$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
				$xml_str .= '<Property Name="Description"></Property>';//描述			
				$xml_str .= '</Object>';
			}		
		}		
		$xml_str .= '</Objects>';
		$xml_str .= '<Mappings>';
		//栏目关系
		$category_id = (!isset($vod_info['nns_category_id'][0]) || empty($vod_info['nns_category_id'][0])) ? CSP_ID . $video_info['nns_category_id'] : CSP_ID . $vod_info['nns_category_id'][0];
		$obj_cate_id = CSP_ID . i_object_guid(26);
		$xml_str .= '<Mapping ParentType="Category" ParentID="'.$category_id.'" ElementType="Series" ElementID="'.$vod_id.'" ObjectID="'.$obj_cate_id.'" Action="' . $action . '">';			
		$xml_str .= '</Mapping>';
		//图片
	    if(!empty($vod_info['nns_image2']))
	    {
			$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
			$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
			if(file_exists($file_img))
			{	
				$obj_pic_id = CSP_ID . i_object_guid(26);			
				$xml_str .= '<Mapping ParentType="Picture" ParentID="'.$pic_id.'" ElementType="Series" ElementID="'.$vod_id.'" ObjectID="'.$obj_pic_id.'" Action="' . $action . '">';
				$xml_str .= '<Property Name="Type">1</Property>'; 			
				$xml_str .= '<Property Name="Sequence">0</Property>';			
				$xml_str .= '</Mapping>';						
			}
	    }		
	    $xml_str .= '</Mappings>';
		$xml_str .= '</ADI>';
		//die($xml_str);
		$guid = np_guid_rand();
		$file_name = 'series_'.$vod_id.'_'.$guid.'.xml';
		$c2_info = array(
			'nns_task_type'=>'Series',
			'nns_task_id'=> isset($vod_info['nns_task_id']) ? $vod_info['nns_task_id'] : null,	
			'nns_task_name'=> isset($vod_info['nns_task_name']) ? $vod_info['nns_task_name'] : null,	
			'nns_action'=>	$action,		
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Series,'.$action,
		);		
		return self::execute_c2($c2_info,$sp_id);		
	}	
	/**
	 * @params array(
	 * nns_id
	 * nns_task_id
	 * )
	 */
	static public function delete_series($params,$sp_id)
	{	
		include dirname(dirname(__FILE__)).'/define.php';
		$action = "DELETE";
		$sp_config = sp_model::get_sp_config($sp_id);
		$series_id = $params['nns_id'];
		$video_info = video_model::get_vod_info($params['nns_id']);
		if(isset($sp_config['import_id_mode']) && strlen($sp_config['import_id_mode']) > 0 && (int)$sp_config['import_id_mode'] > 0)
		{			
			switch ($sp_config['import_id_mode']) 
			{				
				case '1':					
					$series_id = '000000'.$video_info['nns_integer_id'];
					$series_id = str_pad($series_id,32,"0");
					break;
				case '2':
					$series_id = $video_info['nns_asset_import_id'];
					break;
				case '3':
					$series_id = CSP_ID.'000'.$video_info['nns_integer_id'];
					$series_id = str_pad($series_id,32,"0");
					break;
			}			
		}				
		$xml_str .= '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Series" ContentID="' .$series_id. '" Action="' . $action . '" Name="' . htmlspecialchars($video_info['nns_name'],ENT_QUOTES) . '"></Object>';
		//获取图片
		if(empty($video_info['nns_image2']) && !empty($video_info['nns_image_v']))
		{
			$video_info['nns_image2'] = $video_info['nns_image_v'];
		}
		$map_xml = '';
		if(!empty($video_info['nns_image2']))
		{
			$img_save_name = str_replace('.JPG','.jpg',$video_info['nns_image2']);
			$pic_id = CSP_ID . self::get_image_id($img_save_name);
			$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
			if(file_exists($file_img))
			{										 
				$xml_str .= '<Object ElementType="Picture" pictureId="' .$pic_id. '" Action="' . $action . '"></Object>';
				$obj_pic_id = CSP_ID . i_object_guid(26);
				$map_xml = '<Mapping ParentType="Picture" ParentID="'.$pic_id.'" ElementType="Series" ElementID="'.$series_id.'" ObjectID="'.$obj_pic_id.'" Action="' . $action . '"></Mapping>';
			}						
		}
		$xml_str .= '</Objects>';
		//栏目关系
		$db = nn_get_db(NL_DB_READ);
		$cate_sql = "select nns_sp_category_id from nns_mgtvbk_category where nns_org_id='$sp_id' and bind_vod_item='{$video_info['nns_category_id']}'";
		$result_category = nl_db_get_all($cate_sql,$db);
		unset($cate_sql);
		$sp_category = array();
		foreach ($result_category as  $value) 
		{
			$sp_category[] = $value['nns_sp_category_id'];//获取绑定栏目
		}
		$category_id = CSP_ID . $video_info['nns_category_id'];
		if(!empty($sp_category) && isset($sp_category[0]))
		{
			$category_id = CSP_ID . $sp_category[0];
		}
		$obj_cate_id = CSP_ID . i_object_guid(26);
		$xml_str .= '<Mappings>';
		$xml_str .= '<Mapping ParentType="Category" ParentID="'.$category_id.'" ElementType="Series" ElementID="'.$series_id.'" ObjectID="'.$obj_cate_id.'" Action="'.$action.'"></Mapping>';
		$xml_str .= $map_xml;
		$xml_str .= '</Mappings>';
		$xml_str .= '</ADI>';
		//die($xml_str);
		$guid = np_guid_rand();
		$file_name = 'series_'.$series_id.'_'.$guid.'_'.$action.'.xml';
		
		$c2_info = array(
			'nns_task_type'=>'Series',
			'nns_task_id'=>  isset($params['nns_task_id'])?$params['nns_task_id']:null,	
			'nns_task_name'=>  isset($params['nns_task_name'])?$params['nns_task_name']:null,	
			'nns_action'=>	$action,		
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Series,'.$action,
		);		
		return self::execute_c2($c2_info,$sp_id);
	}
	/**
	 * 创建VOD信息
	 * @param 片源信息  $index_media
	 * @param 操作 $action
	 * @param SPID $sp_id
	 */
	static public function build_vod($index_media,$action,$sp_id)
	{
		include_once dirname(dirname(dirname(__FILE__))).'/'.$sp_id.'/define.php';	
	    //获取这个影片的主媒资ID,查询这个媒资是电影还是连续剧
        $is_series = false;
        $vod_info = video_model::get_vod_info($index_media['nns_video_id']);     
        $vod_index_info = video_model::get_vod_index_info($index_media['nns_video_index_id']);     
        $nns_task_name = $index_media['nns_task_name'];           
        $vod_index_info['nns_series_flag'] = 0;
        if($vod_info['nns_all_index'] > 1)
        {//连续剧
            $is_series = true;
            $vod_index_info['nns_series_flag'] = 1;
            $index_ex = video_model::get_vod_ex_info($vod_index_info['nns_import_id'],'index');
        }
        else
        {//影片
            $vod_index_info['nns_name'] = $vod_info['nns_name'];
            $vod_index_info['nns_series_flag'] = 0;
            $vod_ex = video_model::get_vod_ex_info($vod_info['nns_asset_import_id']);
        }
		$program_id = $vod_index_info['nns_id'];//分集GUID
		$vod_id = $program_id;
		//获取SP配置
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['import_id_mode']) && strlen($sp_config['import_id_mode']) > 0 && (int)$sp_config['import_id_mode'] > 0)
		{
			switch ($sp_config['import_id_mode']) 
			{				
				case '1':					
					$vod_id = '001000' .$vod_index_info['nns_integer_id'];
					$vod_id = str_pad($vod_id,32,"0");
					break;
				case '2':
					$vod_id = $vod_index_info['nns_import_id'];
					break;
				case '3'://内容数字组合ID					
					$vod_id = CSP_ID . '001'.$vod_index_info['nns_integer_id'];
					$vod_id = str_pad($vod_id,32,"0");
					break;
			}
			
		}
		$db = nn_get_db(NL_DB_READ);
							
		$xml_str = '<Object ElementType="Program" ContentID="' .$vod_id. '" Action="' . $action . '">';
		if(!empty($vod_index_info['nns_name']) && $is_series)
		{
			$vod_info['nns_name'] = $vod_index_info['nns_name'];
		}
		$xml_str .= '<Property Name="Name">'.htmlspecialchars($vod_info['nns_name'], ENT_QUOTES).'</Property>';
		$media_file_path = '';
		//切小文件模式，直接传递片源m3u8地址,即播控开启切片
		if((int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
		{
			//获取切片完成的片源
			$media_sql = "select nns_file_path from nns_mgtvbk_c2_task where nns_src_id='{$index_media['nns_video_index_id']}' and nns_type='media' and nns_action !='destroy' and nns_status=1 limit 1";
			$media_file = nl_query_by_db($media_sql, $db);
			if(!is_array($media_file))
			{
				return false;//片源还未切片
			}
			$media_file_path = $media_file[0]['nns_file_path'];
		}
		$xml_str .= '<Property Name="FileURL">'.$media_file_path.'</Property>';//切片文件
		$xml_str .= '<Property Name="SeriesFlag">'.$vod_index_info['nns_series_flag'].'</Property>';//0: 普通VOD 1: 连续剧剧集
		$sequence = '';
		if($is_series)
		{
			$sequence = $vod_index_info['nns_index']+1;
			$vod_info['nns_alias_name'] = $index_ex['subordinate_name'];
		}
		if(empty($vod_info['nns_eng_name']))
		{
			$vod_info['nns_eng_name'] = date('YmdHis');
		}
		$xml_str .= '<Property Name="SortName">'.$sequence.'</Property>';//索引名称供界面排序 剧集时必填
		
		$xml_str .= '<Property Name="CPContentID">'.$vod_id.'</Property>';//CP对于该节目的标识 
		$xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
		$xml_str .= '<Property Name="CpContentID">'.$vod_id.'</Property>';//CP内部对于该节目的标识  
		$xml_str .= '<Property Name="OriginalName">'.htmlspecialchars($vod_info['nns_alias_name'], ENT_QUOTES).'</Property>';//原名		
		$xml_str .= '<Property Name="SearchName">'.$vod_info['nns_pinyin'].'</Property>';//搜索名称供界面搜索
		if(!$is_series)
		{//电影取主媒资的数据
			$vod_index_info['nns_actor'] = !empty($vod_info['nns_actor']) ? $vod_info['nns_actor'] : $vod_index_info['nns_actor'];
			$vod_index_info['nns_director'] = !empty($vod_info['nns_director']) ? $vod_info['nns_director'] : $vod_index_info['nns_director'];
			$vod_index_info['nns_area'] = $vod_info['nns_area'];
			$vod_index_info['nns_language']= $vod_info['nns_language'];
			$vod_info['nns_index_show_time'] = empty($vod_info['nns_index_show_time']) ? $vod_info['nns_show_time'] : $vod_index_info['nns_release_time'];
			$vod_index_info['nns_summary'] = $vod_info['nns_summary'];
		}
		if(empty($vod_index_info['nns_actor']))
		{
			$vod_index_info['nns_actor'] = $vod_info['nns_play_role'];
		}
		if(empty($vod_index_info['nns_director']))
		{
			$vod_index_info['nns_director'] = $vod_info['nns_play_role'];
		}
		$actor = str_replace(array('|',' ','/'), ',', $vod_index_info['nns_actor']);
		$director = str_replace(array('|',' ','/'), ',', $vod_index_info['nns_director']);
		$area = str_replace(array('|',' ','/'), ',', $vod_index_info['nns_area']);
		$language = str_replace(array('|',' ','/'), ',', $vod_index_info['nns_language']);
		
		$xml_str .= '<Property Name="ActorDisplay">'.htmlspecialchars($actor, ENT_QUOTES).'</Property>';//演员列表,多个以逗号分隔
		$xml_str .= '<Property Name="WriterDisplay">'.htmlspecialchars($director, ENT_QUOTES).'</Property>';//作者列表
		$xml_str .= '<Property Name="OriginalCountry">'.htmlspecialchars($area, ENT_QUOTES).'</Property>';//国家地区
		$xml_str .= '<Property Name="Language">'.htmlspecialchars($language, ENT_QUOTES).'</Property>';//语言
			
		$show_time = null;
		if($vod_info['nns_index_show_time'] == '0000-00-00 00:00:00' || empty($vod_info['nns_index_show_time']))
		{
			$show_time = $vod_info['nns_show_time'];//影片基本信息上的上映时间
		}
		else
		{
			$show_time = $vod_info['nns_index_show_time'];//分集的上映时间
		}
		
		$xml_str .= '<Property Name="ReleaseYear">' .  date('Y',strtotime($show_time)).'</Property>';//上映年份(YYYY)
		$xml_str .= '<Property Name="OrgAirDate">' . date('Ymd',strtotime($show_time)).'</Property>';//首播日期(YYYYMMDD)
		$xml_str .= '<Property Name="LicensingWindowStart">'. date('YmdHis').'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
		$xml_str .= '<Property Name="LicensingWindowEnd">'. date('YmdHis',time()+ 3*365*24*60*60).'</Property>';//有效结束时间(YYYYMMDDHH24MiSS)
		$xml_str .= '<Property Name="DisplayAsNew">0</Property>';//新到天数
		$xml_str .= '<Property Name="DisplayAsLastChance">300</Property>';//剩余天数
		$xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护    1:有拷贝保护
		$summary = mb_strcut($vod_index_info['nns_summary'], 0,1024,'utf-8');
		$xml_str .= '<Property Name="Description">'.htmlspecialchars($summary, ENT_QUOTES).'</Property>';//节目描述
		$xml_str .= '<Property Name="PriceTaxIn"></Property>';//列表定价		
		$xml_str .= '<Property Name="Status">1</Property>';//状态标志 0:失效 1:生效		
		$xml_str .= '<Property Name="SourceType">1</Property>';//1: VOD 5: Advertisement
		$xml_str .= '<Property Name="ContentProvider">CNTV</Property>';//节目提供商
			
		$keyword = str_replace(array('|',' ','/'), ',', $vod_info['nns_keyword']);
		$keyword = mb_strcut($keyword, 0,256,'utf-8');
		$xml_str .= '<Property Name="KeyWords">'.htmlspecialchars($keyword, ENT_QUOTES).'</Property>';//关键字 多个关键字之间使用分号分隔
		if(empty($vod_info['nns_kind']))
		{
			$vod_info['nns_kind'] = $vod_info['nns_keyword'];
		}
		$tags = str_replace(array('|',' ','/'), ',', $vod_info['nns_kind']);
		$tags = mb_strcut($tags, 0,256,'utf-8');
		$xml_str .= '<Property Name="Tags">'.$tags.'</Property>';//关联标签 多个标签之间使用分号分隔
		$xml_str .= '<Property Name="ViewPoint"></Property>';//看点
		$xml_str .= '<Property Name="StarLevel">5</Property>';//推荐星级 从 1－10，数字越大推荐星 级越高，缺省为 6 ，为 3 颗星 
		$xml_str .= '<Property Name="Rating"></Property>';//限制类别 
		$xml_str .= '<Property Name="Awards"></Property>';//所含奖项
		$xml_str .= '<Property Name="Length">' . round($vod_index_info['nns_time_len']/60) . '</Property>';//播放时长
		$xml_str .= '<Property Name="ProgramType">'.self::$program_type[$vod_info['nns_view_type']].'</Property>';//节目内容类型 字符串，表示内容类型，例如：电影，连续剧，新闻，体育…

        //修改说明：爱上悦me同步CP信息新增下发【内容提供商ID】
        //修改人员：kan.yang@starcor.com
        //修改时间：2018-05-14 14:36:00
        $arr_cntv_cp_relation = get_config_v2('g_cntv_me_cp_relation');
        if((!isset($arr_cntv_cp_relation) || empty($arr_cntv_cp_relation)) && isset(self::$arr_cp_relation))
        {
            $arr_cntv_cp_relation = self::$arr_cp_relation;
        }
        if(isset($arr_cntv_cp_relation) && !empty($arr_cntv_cp_relation))
        {
            $str_producer = isset($vod_info['nns_producer']) && strlen($vod_info['nns_producer']) > 0 ? $vod_info['nns_producer'] : '';
            if(isset($arr_cntv_cp_relation[$vod_info['nns_producer']]))
            {
                $str_producer = $arr_cntv_cp_relation[$vod_info['nns_producer']];
            }
            elseif(isset($arr_cntv_cp_relation['default']))
            {//如果上游cpid为空，或者不在对照表里，就传递一个默认值

                $str_producer = $arr_cntv_cp_relation['default'];
            }
            $xml_str .= '<Property Name="Reserve1">' . $str_producer . '</Property>';
        }
        else
        {
            $xml_str .= '<Property Name="Reserve1"></Property>';//保留字段
        }

		$xml_str .= '<Property Name="Reserve2"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve3"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve4"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve5"></Property>';//保留字段s
		$xml_str .= '<Property Name="UniContentId"></Property>';//所属全局内容一标识
		
		$xml_str .= '</Object>';
		$pic_id = '';
		if($is_series)
		{//电视剧
//			if(!empty($vod_index_info['nns_image']))
//			{
//				$img_save_name = str_replace('.JPG','.jpg',$vod_index_info['nns_image']);
//				$pic_id = CSP_ID . self::get_image_id($img_save_name);
//				$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
//				if(file_exists($file_img))
//				{
//					$pic_url = self::get_image_url($img_save_name,$sp_id);
//					$xml_str .= '<Object ElementType="Picture" pictureId="' .$pic_id.'" Action="' . $action . '">';
//					$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
//					$xml_str .= '<Property Name="Description"></Property>';//描述			
//					$xml_str .= '</Object>';
//				}
//			}
		}
		else 
		{//电影
			//图片
			if(empty($vod_info['nns_image0']) && !empty($vod_info['nns_image_v']))
			{
				$vod_info['nns_image0'] = $vod_info['nns_image_v'];
			}	
			if(!empty($vod_info['nns_image0']))
			{
				$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image0']);
				$pic_id = CSP_ID . self::get_image_id($img_save_name);
				$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
//				var_dump($file_img);die;
				if(file_exists($file_img))
				{
					$pic_url = self::get_image_url($img_save_name,$sp_id);
					$xml_str .= '<Object ElementType="Picture" pictureId="' .$pic_id. '" Action="' . $action . '">';
					$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
					$xml_str .= '<Property Name="Description"></Property>';//描述			
					$xml_str .= '</Object>';
				}
			}
		}			
		$map_xml_str = '';	
		//如果是连续剧分集，绑定到连续剧
		if($is_series)
		{
			$video_id = $vod_info['nns_id'];	
			if(isset($sp_config['import_id_mode']) && strlen($sp_config['import_id_mode']) > 0 && (int)$sp_config['import_id_mode'] > 0)
			{
				switch ($sp_config['import_id_mode']) 
				{				
					case '1':					
						$video_id = '000000' . $vod_info['nns_integer_id'];
						$video_id = str_pad($video_id,32,"0");
						break;
					case '2':
						$video_id = $vod_info['nns_asset_import_id'];
						break;
					case '3'://内容数字组合ID					
						$video_id = CSP_ID . '000'.$vod_info['nns_integer_id'];
						$video_id = str_pad($video_id,32,"0");
						break;
				}			
			}
			$obj_pro_id = CSP_ID . i_object_guid(26);
			$map_xml_str .= '<Mapping ParentType="Series" ParentID="'.$video_id.'" ElementType="Program" ElementID="'.$vod_id.'" ObjectID="'.$obj_pro_id.'" Action="REGIST">';
			$map_xml_str .= '</Mapping>';
			//图片
//		    if(!empty($vod_index_info['nns_image']))
//		    {
//				$img_save_name = str_replace('.JPG','.jpg',$vod_index_info['nns_image']);
//				$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
//				if(file_exists($file_img))
//				{
//					$obj_pic_id = CSP_ID . i_object_guid(26);
//					$map_xml_str .= '<Mapping ParentType="Picture" ParentID="'.$pic_id.'" ElementType="Program" ElementID="'.$vod_id.'" ObjectID="'.$obj_pic_id.'" Action="' . $action . '">';
//					//Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
//					//10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
//					$map_xml_str .= '<Property Name="Type">1</Property>'; 			
//					$map_xml_str .= '<Property Name="Sequence">0</Property>';//
//					$map_xml_str .= '</Mapping>';
//				}
//		    }						
		}
		else
		{
			//栏目关系
			$cate_sql = "select nns_sp_category_id from nns_mgtvbk_category where nns_org_id='$sp_id' and bind_vod_item='{$vod_info['nns_category_id']}'";
			$result_category = nl_db_get_all($cate_sql,$db);
			unset($cate_sql);
			$sp_category = array();
			foreach ($result_category as  $value) 
			{
				$sp_category[] = $value['nns_sp_category_id'];
			}
			$category_id = CSP_ID . $vod_info['nns_category_id'];
			if(!empty($sp_category) && isset($sp_category[0]))
			{
				$category_id = CSP_ID . $sp_category[0];
			}
			$obj_cate_id = CSP_ID . i_object_guid(26);
			$map_xml_str .= '<Mapping ParentType="Category" ParentID="'.$category_id.'" ElementType="Program" ElementID="'.$vod_id.'" ObjectID="'.$obj_cate_id.'" Action="' . $action . '">';			
			$map_xml_str .= '</Mapping>';
			//图片
		    if(!empty($vod_info['nns_image0']))
		    {
				$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image0']);
				$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
				if(file_exists($file_img))
				{
					$obj_pic_id = CSP_ID . i_object_guid(26);
					$map_xml_str .= '<Mapping ParentType="Picture" ParentID="'.$pic_id.'" ElementType="Program" ElementID="'.$vod_id.'" ObjectID="'.$obj_pic_id.'" Action="' . $action . '">';
					//Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
					//10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
					$map_xml_str .= '<Property Name="Type">1</Property>'; 			
					$map_xml_str .= '<Property Name="Sequence">0</Property>';//
					$map_xml_str .= '</Mapping>';
				}
		    }
		}

		//echo $xml_str;die;	
		$xml_info = array(
			'object_xml' => $xml_str,
			'mapping_xml' => $map_xml_str,
		);		
		return $xml_info;
	}	
	/**
	 * @param $asset_info 主媒资信息
	 * @param $index_info 分集信息
	 * @param $is_series bool true为连续剧 false为影片
	 * @param $sp_config SP配置
	 * @param $action 操作
	 */
	static public function bulid_delete_vod($asset_info,$index_info,$is_series,$sp_config,$action)
	{
		include_once dirname(dirname(__FILE__)).'/define.php';
		$asset_id = $asset_info['nns_id'];
		$index_id = $index_info['nns_id'];
		$name = $asset_info['nns_name'];
		if(isset($sp_config['import_id_mode']) && strlen($sp_config['import_id_mode']) > 0 && (int)$sp_config['import_id_mode'] > 0)
		{			
			switch ($sp_config['import_id_mode']) 
			{				
				case '1':					
					if($is_series)
					{
						$asset_id = '000000'.$asset_info['nns_integer_id'];	
						$asset_id = str_pad($asset_id,32,"0");
						$name = $index_info['nns_name'];
					}			
					$index_id = '001000'.$index_info['nns_integer_id'];
					$index_id = str_pad($index_id,32,"0");
					break;
				case '2':
					if($is_series)
					{
						$asset_id = $asset_info['nns_asset_import_id'];
						$name = $index_info['nns_name'];
					}
					
					$index_id = $index_info['nns_import_id'];
					break;
				case '3':
					if($is_series)
					{
						$asset_id = CSP_ID.'000'.$asset_info['nns_integer_id'];
						$asset_id = str_pad($asset_id,32,"0");
						$name = $index_info['nns_name'];
					}
					$index_id = CSP_ID.'001'.$index_info['nns_integer_id'];
					$index_id = str_pad($index_id,32,"0");
					break;
			}			
		}
		$xml_str = '<Object ElementType="Program" ContentID="' .$index_id. '" Action="' . $action . '" Name="' . htmlspecialchars($name,ENT_QUOTES) . '"></Object>';	
		
		$map_xml = '';
		if($is_series)
		{//电视剧
			$obj_id = CSP_ID.i_object_guid(26);
			$map_xml = '<Mapping ParentType="Series" ParentID="'.$asset_id.'" ElementType="Program" ElementID="'.$index_id.'" ObjectID="'.$obj_id.'" Action="'.$action.'"></Mapping>';	
//			if(!empty($index_info['nns_image']))
//			{
//				$img_save_name = str_replace('.JPG','.jpg',$index_info['nns_image']);
//				$pic_id = CSP_ID . self::get_image_id($img_save_name);
//				$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
//				if(file_exists($file_img))
//				{
//					$obj_pic_id = CSP_ID.i_object_guid(26);
//					$xml_str .= '<Object ElementType="Picture" pictureId="'.$pic_id.'" Action="'.$action.'"></Object>';
//					$map_xml .= '<Mapping ParentType="Picture" ParentID="'.$pic_id.'" ElementType="Program" ElementID="'.$index_id.'" ObjectID="'.$obj_pic_id.'" Action="'.$action.'"></Mapping>';	
//				}
//			}
		}
		else 
		{//电影
			if(empty($asset_info['nns_image0']) && !empty($asset_info['nns_image_v']))
			{
				$asset_info['nns_image0'] = $asset_info['nns_image_v'];
			}	
			if(!empty($asset_info['nns_image0']))
			{
				$img_save_name = str_replace('.JPG','.jpg',$asset_info['nns_image0']);
				$pic_id = CSP_ID . self::get_image_id($img_save_name);
				$file_img = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg/'.$img_save_name;
				if(file_exists($file_img))
				{
					$obj_pic_id = CSP_ID.i_object_guid(26);
					$xml_str .= '<Object ElementType="Picture" pictureId="'.$pic_id.'" Action="'.$action.'"></Object>';
					$map_xml .= '<Mapping ParentType="Picture" ParentID="'.$pic_id.'" ElementType="Program" ElementID="'.$index_id.'" ObjectID="'.$obj_pic_id.'" Action="'.$action.'"></Mapping>';
				}
			}
		}
		return array('object_xml' => $xml_str,'map_xml' => $map_xml);
	}
	/**
	 * 电影或连续剧分集修改
	 * 
	 */
	static public function update_vod($info,$sp_id)
	{	
		return self::add_movies_by_vod_index($info, $sp_id,'Program','UPDATE');
	}
	/**
	 * 注入片源（以分集为单位,切片完成后调用）
	 * $index_media array(
	 * 			'nns_video_id'
	 * 			'nns_video_index_id'
	 * 			'nns_task_id'
	 * 			'nns_new_dir'
	 * 			'nns_media_ids'
	 * )
	 */
	static public function add_movies_by_vod_index($index_media,$sp_id,$c2_type=null,$action=null)
	{
		include_once dirname(dirname(dirname(__FILE__))).'/'.$sp_id.'/define.php';
		DEBUG && i_write_log_core('--注入片源--');
		$db = nn_get_db(NL_DB_WRITE);

		$sql = "select nns_pinyin from nns_vod where nns_id='".$index_media['nns_video_id']."'";
		$pinyin = nl_db_get_col($sql,$db);

		$action = empty($action) ? 'REGIST' : $action;		
		$sql = "select * from nns_vod_media where nns_deleted != 1 and nns_vod_id='{$index_media['nns_video_id']}' and nns_vod_index_id='{$index_media['nns_video_index_id']}' and nns_id='{$index_media['nns_media_id']}' order by nns_kbps desc limit 1";		
		$medias = nl_db_get_all($sql,$db);
		if(!is_array($medias) && count($medias) <= 0)
		{
			DEBUG && i_write_log_core('--没有片源--');
			nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=1,nns_action='destroy',nns_epg_status=97 where nns_id='{$index_media['nns_task_id']}'", $db);
		}
		
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';					
		$xml_str .= '<Objects>';
		$xml_arr = self::build_vod($index_media, $action, $sp_id);
		$xml_str .= $xml_arr['object_xml'];
		$sp_config = sp_model::get_sp_config($sp_id);
		$program_id = $index_media['nns_media_id'];
		$media_id = $program_id;
		if(isset($sp_config['import_id_mode']) && strlen($sp_config['import_id_mode']) > 0 && (int)$sp_config['import_id_mode'] > 0)
		{
			$video_info = video_model::get_vod_media_info($index_media['nns_media_id']);
			switch ($sp_config['import_id_mode']) {				
				case '1'://数字ID					
					$program_id = '002000'.$video_info['nns_integer_id'];
					$program_id = str_pad($program_id,32,"0");
					break;
				case '2'://原始ID
					$program_id = $video_info['nns_import_id'];
					break;
				case '3'://内容数字组合ID					
					$program_id = CSP_ID . '002'.$video_info['nns_integer_id'];
					$program_id = str_pad($program_id,32,"0");
					break;
			}
			
		}              
		//判断切片的方式
		if((int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
		{//播控切片
			if(empty($index_media['nns_date']))
			{
				$index_media['nns_date'] = nl_db_get_col("select nns_date from nns_mgtvbk_clip_task where nns_id='{$index_media['nns_clip_task_id']}'", $db);
			}		
			$url = MOVIE_FTP.$index_media['nns_date'].'/'.$index_media['nns_clip_task_id'].'/'.$pinyin.'-'.$media['nns_vod_index'].'.m3u8';
			if(!empty($index_media['nns_file_path']))
			{
				$url = MOVIE_FTP.$index_media['nns_file_path'];
			}				
			$bool = self::check_ftp_file($url);
			if($bool===false)
			{
				DEBUG && i_write_log_core('path_fail----'.$url,$sp_id.'/path_fail');
				nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='{$index_media['nns_task_id']}'", $db);
				include_once dirname(dirname(dirname(__FILE__))).'/models/queue_task_model.php';
				$queue_task_model = new queue_task_model();				
				$queue_task_model->q_re_clip($index_media['nns_task_id']);
				$queue_task_model=null;
				return false;
			}
		}
		else //CDN切片
		{
			$url = $medias[0]['nns_url'];
			//$url = 'ftp://devtest:cacheyun@106.39.160.116/5c21fae44d9e3de0fa9640050a4e5c44_h2642200000mp296.ts';
		}
		
		$xml_str .= '<Object ElementType="Movie" PhysicalContentID="' .$program_id. '" Action="' . $action . '" Type="1">';//媒体类型1:正片 2:预览片	
		$xml_str .= '<Property Name="HotDegree">2</Property>';//热度排名：1（低）， 2 （普 通），3（高）		
		$xml_str .= '<Property Name="CPContentID">'.$program_id.'</Property>';
		$xml_str .= '<Property Name="FileURL">' .$url. '</Property>';//媒体文件URL,ftp://username:password@ip:port/...  标准FTP协议
		$xml_str .= '<Property Name="Duration">' . $medias[0]['nns_file_time_len'] . '</Property>';//播放时长HHMISSFF （时分秒帧）
		$xml_str .= '<Property Name="FileSize">0</Property>';//文件大小，单位为Byte
		$xml_str .= '<Property Name="SourceDRMType">0</Property>';//0: No DRM 1: BES DRM
		$xml_str .= '<Property Name="DestDRMType">0</Property>';//0: No DRM 1: BES DRM 
		$xml_str .= '<Property Name="AudioType">1</Property>';//0: 其他 1: Monaural 单声道 2: Stereo 多声道 3: Two-nation monaural 双单声道 4: Two-nation stereo 双多声道  5: AC3(5:1 channel) AC3声道
		$xml_str .= '<Property Name="ScreenFormat">1</Property>';//0: 4x3 1: 16x9(Wide)
		$xml_str .= '<Property Name="ClosedCaptioning">1</Property>';//0:无字幕 1:有字幕
		$xml_str .= '<Property Name="BitRateType">4</Property>';//码流 1: 400k 2：700K 3: 1.3M 4：2M 5：2.5M 6:  8M 7：10M 
		$xml_str .= '<Property Name="VideoType">1</Property>';//编码格式： 1. H.264 2. MPEG4 3. AVS 4. MPEG2 5. MP3 6. WMV 7. H.265 
		$xml_str .= '<Property Name="AudioEncodingType">1</Property>';//编码格式：1.	MP2 2.	AAC 3.	AMR
		$xml_str .= '<Property Name="Resolution">1</Property>';//分辨率类型：1:QCIF 2:QVGA 3:2/3 D1 4:3/4 D1 5:D1 6:720P 7:1080i 8:1080P
		$video_profile =1;
        $mode = strtolower($medias[0]['nns_mode']);
        switch($mode)
        {
        	case 'std':
        		$video_profile = 1;
        		break;
            case 'hd':
                $video_profile = 5;
                break;
            case 'low':
                $video_profile = 3;
                break;
        } 	
		$xml_str .= '<Property Name="VideoProfile">'.$video_profile.'</Property>';//1:Simple 2:Advanced Simple 3:Baseline 4:Main 5:High 6:JiZhun
		$xml_str .= '<Property Name="SystemLayer">1</Property>';//1:TS 2:3GP
		$xml_str .= '<Property Name="Domain">0x01</Property>';//服务类型
		$xml_str .= '<Property Name="SourceBitRate">'.$medias[0]['nns_file_size'].'</Property>';//原始码率
		$xml_str .= '<Property Name="SliceBitRateType">'.self::$file_mapping[$medias[0]['nns_file_size']].'</Property>';//切片码率模型
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		
		$nns_video_index_id = $index_media['nns_video_index_id'];	
		if(isset($sp_config['import_id_mode'])&&strlen($sp_config['import_id_mode'])>0&&(int)$sp_config['import_id_mode']>0)
		{
			$video_info = video_model::get_vod_index_info($index_media['nns_video_index_id']);
			switch ($sp_config['import_id_mode']) 
			{				
				case '1':					
					$nns_video_index_id = '001000'.$video_info['nns_integer_id'];
					$nns_video_index_id = str_pad($nns_video_index_id,32,"0");
					break;
				case '2':
					$nns_video_index_id = $video_info['nns_import_id'];
					break;
				case '3':
					$nns_video_index_id = CSP_ID.'001'.$video_info['nns_integer_id'];
					$nns_video_index_id = str_pad($nns_video_index_id,32,"0");
					break;
			}
			
		}	
		$xml_str .= '<Mappings>';
		$xml_str .= $xml_arr['mapping_xml'];
		$obj_media_id = CSP_ID . i_object_guid(26);
		$xml_str .= '<Mapping ParentType="Program" ParentID="'.$nns_video_index_id.'" ElementType="Movie" ElementID="'.$program_id.'" ObjectID="'.$obj_media_id.'" Action="'.$action.'">';
		$xml_str .= '</Mapping>';
		$xml_str .= '</Mappings>';	
		$xml_str .= '</ADI>';	
		//die($xml_str);
		$guid = np_guid_rand();
		$file_name = 'vod_media_'.$program_id.'_'.$guid.'_'.$action.'.xml';		
		$c2_info = array(
			'nns_task_type'=> empty($c2_type) ? 'Movie' : $c2_type,
			'nns_task_id'=> isset($index_media['nns_task_id']) ? $index_media['nns_task_id'] : null,
			'nns_task_name'=> isset($index_media['nns_task_name']) ? $index_media['nns_task_name'] : null,	
			'nns_action'=>	$action,				
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Movie,'.$action,
		);
		//切片任务开启
		if((int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
		{	
			//修改切片的状态		
			$clip_task_id = $index_media['nns_clip_task_id'];		
			//更改状态
			$dt = date('Y-m-d H:i:s');
			$set_state = array(
				'nns_state' => clip_task_model::TASK_C_STATE_C2_HANDLE,
				'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_HANDLE],
				'nns_modify_time'=>$dt,
			);
			clip_task_model::update_task($clip_task_id, $set_state);				
			//任务日志	
			$task_log = array(
				'nns_task_id' => $clip_task_id,
				'nns_state'   => clip_task_model::TASK_C_STATE_C2_HANDLE,
				'nns_desc'    => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_HANDLE],
			);	
			clip_task_model::add_task_log($task_log);
		}		
		return self::execute_c2($c2_info,$sp_id);	
	}
	/**
	 * 删除影片
	 * params array(
	 * nns_id,
	 * nns_task_id
	 * )
	 */
	static public function delete_movie($params,$sp_id)
	{
		include dirname(dirname(__FILE__)).'/define.php';
		$action = "DELETE";
		$movie_id = $params['nns_id'];
		$media_info = video_model::get_vod_media_info($params['nns_id']);
		
		$asset_info = video_model::get_vod_info($media_info['nns_vod_id']);
		$index_info = video_model::get_vod_index_info($media_info['nns_vod_index_id']);
		
		$sp_config = sp_model::get_sp_config($sp_id);		
		$is_series = true;//连续剧
		if($asset_info['nns_all_index'] <= 1)//电影
		{
			$is_series = false;
		}	
		$vod_xml_info = self::bulid_delete_vod($asset_info,$index_info,$is_series,$sp_config,$action);
		$index_id = $index_info['nns_id'];
		if(isset($sp_config['import_id_mode']) && strlen($sp_config['import_id_mode']) > 0 && (int)$sp_config['import_id_mode'] > 0)
		{			
			switch ($sp_config['import_id_mode']) 
			{				
				case '1':			
					$index_id = '001000'.$index_info['nns_integer_id'];
					$index_id = str_pad($index_id,32,"0");	
						
					$movie_id = '002000'.$index_info['nns_integer_id'];
					$movie_id = str_pad($movie_id,32,"0");
					break;
				case '2':
					$index_id = $index_info['nns_import_id'];
					
					$movie_id = $media_info['nns_import_id'];
					break;
				case '3':
					$index_id = CSP_ID.'001'.$index_info['nns_integer_id'];
					$index_id = str_pad($index_id,32,"0");
					
					$movie_id = CSP_ID.'002'.$media_info['nns_integer_id'];
					$movie_id = str_pad($movie_id,32,"0");
					break;
			}			
		}
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';
		$xml_str .= $vod_xml_info['object_xml']; 		
		$xml_str .= '<Object ElementType="Movie" PhysicalContentID="' .$movie_id. '" Action="' . $action . '" Type="1"></Object>';	
		$xml_str .= '</Objects>';
		
		$xml_str .= '<Mappings>';
		if(!$is_series)
		{//影片有category
			//栏目关系
			$db = nn_get_db(NL_DB_READ);
			$cate_sql = "select nns_sp_category_id from nns_mgtvbk_category where nns_org_id='$sp_id' and bind_vod_item='{$asset_info['nns_category_id']}'";
			$result_category = nl_db_get_all($cate_sql,$db);
			unset($cate_sql);
			$sp_category = array();
			foreach ($result_category as  $value) 
			{
				$sp_category[] = $value['nns_sp_category_id'];//获取绑定栏目
			}
			$category_id = CSP_ID . $video_info['nns_category_id'];
			if(!empty($sp_category) && isset($sp_category[0]))
			{
				$category_id = CSP_ID . $sp_category[0];
			}
			$obj_cate_id = CSP_ID . i_object_guid(26);
			$xml_str .= '<Mapping ParentType="Category" ParentID="'.$category_id.'" ElementType="Program" ElementID="'.$index_id.'" ObjectID="'.$obj_cate_id.'" Action="'.$action.'"></Mapping>';
		}
		$xml_str .= $vod_xml_info['map_xml'];
		$obj_id = CSP_ID . i_object_guid(26);
		$xml_str .= '<Mapping ParentType="Program" ParentID="'.$index_id.'" ElementType="Movie" ElementID="'.$movie_id.'" ObjectID="'.$obj_id.'" Action="DELETE"></Mapping>';
		$xml_str .= '</Mappings>';
		$xml_str .= '</ADI>';
		//die($xml_str);
		$guid = np_guid_rand();
		$file_name = 'movie_'.$movie_id.'_'.$guid.'_'.$action.'.xml';
				
		$c2_info = array(
			'nns_task_type'=>'Movie',
			'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,	
			'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,
			'nns_action'=>	$action,		
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Movie,'.$action,
		);
		
		if((int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
		{
			//更改状态
			$dt = date('Y-m-d H:i:s');
			$set_state = array(
				'nns_state' => clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE,
				'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE],
				'nns_modify_time'=>$dt,
			);
			clip_task_model::update_task($params['nns_clip_task_id'], $set_state);					
			//任务日志	
			$task_log = array(
				'nns_task_id' => $params['nns_clip_task_id'],
				'nns_state'   => clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE,
				'nns_desc'    => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE],
			);	
			clip_task_model::add_task_log($task_log);
		}
		return self::execute_c2($c2_info,$sp_id);		
	}
	/**
	 * 添加内容栏目
	 */
	static public function add_categoy($category_info,$sp_id)
	{
		$action = 'REGIST';
		return self::do_category($category_info,$action,$sp_id);
	}
	/**
	 * 修改内容栏目
	 */	
	static public function update_category($category_info,$sp_id)
	{
		$action = 'UPDATE';
		return self::do_category($category_info,$action,$sp_id);
	}
	/**
	 * 删除栏目
	 */
	static public function delete_category($param,$sp_id)
	{		
		include_once dirname(dirname(__FILE__)).'/define.php';
		$category_id = $param['nns_id'];
		$action = "DELETE";
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Category" CategoryID="' .CSP_ID.$category_id. '" Action="' . $action . '">';
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
				
		$file_name = 'category_'.$category_id.'_'.$action.'.xml';

		
		$c2_info = array(
			'nns_task_type'=>'Category',
			'nns_task_id'=> isset($param['nns_task_id'])?$param['nns_task_id']:null,
			'nns_task_name'=> isset($param['nns_task_name'])?$param['nns_task_name']:null,
			'nns_action'=>	$action,
			'nns_url' =>$file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Category,'.$action,
		);		
		return  self::execute_c2($c2_info,$sp_id);	
	}
	/**
	 * 增加内容栏目
	 * $category_info array(
	 * 'nns_category_id'
	 * 'nns_parent_id'
	 * 'nns_name'
	 * )
	 */
	static public function do_category($category_info,$action,$sp_id)
	{
		include_once dirname(dirname(__FILE__)).'/define.php';
		$sort = empty($category_info['nns_sort']) ? 0 : $category_info['nns_sort'];
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Category" CategoryID="' .CSP_ID.$category_info['nns_category_id']. '" Action="' . $action . '">';
		$xml_str .= '<Property Name="Name">'.$category_info['nns_name'].'</Property>';
		if(empty($category_info['nns_parent_id']) || !isset($category_info['nns_parent_id']))
		{
			$parent_id = 'null';
		}
		else 
		{
			$parent_id = CSP_ID.$category_info['nns_parent_id'];
		}
		$xml_str .= '<Property Name="ParentID">'.$parent_id.'</Property>';
		$xml_str .= '<Property Name="Sequence">'.$sort.'</Property>';
		$xml_str .= '<Property Name="Status">1</Property>';
		$xml_str .= '<Property Name="Description"></Property>';
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
	
		$file_name = 'category_'.$category_info['nns_category_id'].'_'.$action.'.xml';

		
		$c2_info = array(
			'nns_task_type'=>'Category',
			'nns_task_id'=> isset($category_info['nns_task_id'])?$category_info['nns_task_id']:null,
			'nns_task_name'=> isset($category_info['nns_task_name'])?$category_info['nns_task_name']:null,
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
	
			'nns_desc' => 'Category,'.$action,
		);		
		return self::execute_c2($c2_info,$sp_id);
	}

    /**
     * @description:爱上项目，主媒资上下线同步注入到cdn
     * @author:xinxin.deng
     * @date: 2018/1/10 14:19
     * @param $video_info
     * @param $action
     * @param $sp_id
     * @return bool
     */
	static public function do_series_line($vod_info, $action, $sp_id)
    {
        $vod_id = $vod_info['nns_id'];
        include_once dirname(dirname(__FILE__)) . '/define.php';
        if (empty($vod_info['nns_task_name']))
        {
            $vod_info['nns_task_name'] = $vod_info['nns_name'];
        }
        $xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        $xml_str .= '<Objects>';
        $sp_config = sp_model::get_sp_config($sp_id);
        if (isset($sp_config['import_id_mode']) && strlen($sp_config['import_id_mode']) > 0 && (int)$sp_config['import_id_mode'] > 0)
        {
            switch ($sp_config['import_id_mode']) {
                case '1':
                    $vod_id = '000000'.$vod_info['nns_integer_id'];
                    $vod_id = str_pad($vod_id,32,"0");
                    break;
                case '2':
                    $vod_id = $vod_info['nns_import_id'];
                    break;
                case '3':
                    $vod_id = $sp_config['import_csp_id'].'000'.$vod_info['nns_integer_id'];
                    $vod_id = str_pad($vod_id,32,"0");
                    break;
                case '4':
                    $arr_csp_id = explode("|", $sp_config['import_csp_id']);
                    $str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
                    $lest_num = 32-$str_lenth;
                    $vod_id = $arr_csp_id[0].'1'.str_pad($vod_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
                    break;
            }
        }

        $xml_str .= '<Object ElementType="Series" ContentID="' . $vod_id . '" Action="' . $action . '">';
        $xml_str .= '<Property Name="Name">' . htmlspecialchars($vod_info['nns_name'], ENT_QUOTES) . '</Property>';
        $xml_str .= '<Property Name="LicensingWindowStart">' . date('YmdHis') . '</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
        $xml_str .= '<Property Name="LicensingWindowEnd">' . date('YmdHis', time() + 3 * 365 * 24 * 60 * 60) . '</Property>';//有效结束时间(YYYYMMDDHH24MiSS)
        $xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
        $xml_str .= '<Property Name="OriginalName"></Property>';//原名
        $xml_str .= '<Property Name="SortName"></Property>';//索引名称供界面排序
        $xml_str .= '<Property Name="SearchName"></Property>';//搜索名称供界面搜索
        $xml_str .= '<Property Name="OrgAirDate"></Property>';//首播日期(YYYYMMDD)
        $xml_str .= '<Property Name="CPContentID"></Property>';//CP 内部对于该对象的唯一标识，全局唯一标识
        $xml_str .= '<Property Name="DisplayAsNew"></Property>';//新到天数
        $xml_str .= '<Property Name="DisplayAsLastChance"></Property>';//剩余天数
        $xml_str .= '<Property Name="Macrovision"></Property>';//拷贝保护标志0:无拷贝保护    1:有拷贝保护
        $xml_str .= '<Property Name="Price"></Property>';//含税定价
        $xml_str .= '<Property Name="VolumnCount"></Property>';//总集数
        $xml_str .= '<Property Name="Status"></Property>';//状态标志,0:失效 1:生效
        $xml_str .= '<Property Name="Description"></Property>';//描述信息
        $xml_str .= '<Property Name="ContentProvider"></Property>';//节目提供商
        $xml_str .= '<Property Name="KeyWords"></Property>';//关键字
        $xml_str .= '<Property Name="Tags"></Property>';//关联标签
        $xml_str .= '<Property Name="ViewPoint"></Property>';//看点,非常简短的剧情描述
        $xml_str .= '<Property Name="StarLevel"></Property>';//推荐星级
        $xml_str .= '<Property Name="Rating"></Property>';//限制类别 采用国际通用的 Rating 等级
        $xml_str .= '<Property Name="Awards"></Property>';//所含奖项 多个奖项之间使用；分隔
        $xml_str .= '<Property Name="Reserve1"></Property>';//保留字段
        $xml_str .= '<Property Name="Reserve2"></Property>';//保留字段
        $xml_str .= '<Property Name="Reserve3"></Property>';//保留字段
        $xml_str .= '<Property Name="UniContentId"></Property>';//关联内容唯一标识
        $xml_str .= '</Object>';
        //上下线多剧集剧头时，同时包含多剧集。----暂时不用
        /*if ($video_info['nns_all_index'] > 1)
        {
            $video_index_list = video_model::get_vod_index_list($video_info['nns_id']);
            if (is_array($video_index_list) && count($video_index_list) > 0)
            {
                foreach ($video_index_list as $program)
                {
                    //设定为连续剧剧集标识
                    $program['nns_series_flag'] = 1;
                    $xml_str .= self::build_program_line($program, $action);
                }
            }
        }*/
        $xml_str .= '</Objects>';
        $xml_str .= '<Mappings>';

        $db = nn_get_db(NL_DB_READ);
        $cate_sql = "select nns_sp_category_id from nns_mgtvbk_category where nns_org_id='$sp_id' and bind_vod_item='{$vod_info['nns_category_id']}'";
        $result_category = nl_db_get_all($cate_sql,$db);
        unset($cate_sql);
        $sp_category = array();
        if (is_array($result_category))
        {
            foreach ($result_category as  $value)
            {
                $sp_category[] = $value['nns_sp_category_id'];//获取绑定栏目
            }
        }
        $category_id = $sp_config['import_csp_id'] . $vod_info['nns_category_id'];
        if(!empty($sp_category) && isset($sp_category[0]))
        {
            $category_id = $sp_config['import_csp_id'] . $sp_category[0];
        }

        $obj_cate_id = $sp_config['import_csp_id'] . i_object_guid(26);
        $xml_str .= '<Mapping ParentType="Category" ParentID="'.$category_id.'" ElementType="Series" ElementID="'.$vod_id.'" ObjectID="'.$obj_cate_id.'" Action="' . $action . '">';
        $xml_str .= '</Mapping>';
        $xml_str .= '</Mappings>';
        $xml_str .= '</ADI>';
        $guid = np_guid_rand();
        $file_name = 'series_' . $vod_id . '_' . $guid . '.xml';
        $c2_info = array(
            'nns_task_type' => 'Series',
            'nns_task_id' => $vod_info['nns_id'],
            'nns_task_name' => isset($vod_info['nns_task_name']) ? $vod_info['nns_task_name'] : null,
            'nns_action' => $action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => 'Series,' . $action,
        );
        return self::execute_c2($c2_info, $sp_id);
    }

    /**
     * @description:爱上项目，剧集上下线同步注入到cdn
     * @author:xinxin.deng
     * @date: 2018/1/10 14:19
     * @param $program_info
     * @param $action
     * @param $sp_id
     * @return bool
     */
    static public function do_program_line($program_info, $action, $sp_id)
    {
        $program_id = $program_info['nns_id'];
        include_once dirname(dirname(__FILE__)) . '/define.php';
        if (empty($program_info['nns_task_name']))
        {
            $program_info['nns_task_name'] = $program_info['nns_name'];
        }
        $xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        $xml_str .= '<Objects>';
        if (!isset($program_info['nns_series_flag']) || strlen($program_info['nns_series_flag']) < 0)
        {
            $program_info['nns_series_flag'] = 1;
        }
        $index_import_id = $program_info['nns_import_id'];
        $sp_config = sp_model::get_sp_config($sp_id);
        if (isset($sp_config['import_id_mode']) && strlen($sp_config['import_id_mode']) > 0 && (int)$sp_config['import_id_mode'] > 0)
        {
            switch ($sp_config['import_id_mode']) {
                case '1':
                    $index_import_id = '000000'.$program_info['nns_integer_id'];
                    $index_import_id = str_pad($index_import_id,32,"0");
                    break;
                case '2':
                    $index_import_id = $program_info['nns_import_id'];
                    break;
                case '3':
                    $index_import_id = $sp_config['import_csp_id'].'001'.$program_info['nns_integer_id'];
                    $index_import_id = str_pad($index_import_id,32,"0");
                    break;
                case '4':
                    $arr_csp_id = explode("|", CSP_ID);
                    $str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
                    $lest_num = 32-$str_lenth;
                    $index_import_id = $arr_csp_id[0].'1'.str_pad($program_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
                    break;
            }
        }
        $xml_str .= self::build_program_line($program_info, $action, $index_import_id);

        $xml_str .= '</Objects>';
        $xml_str .= '<Mappings>';

        $db = nn_get_db(NL_DB_READ);
        $cate_sql = "select nns_sp_category_id from nns_mgtvbk_category where nns_org_id='$sp_id' and bind_vod_item='{$program_info['nns_category_id']}'";
        $result_category = nl_db_get_all($cate_sql,$db);
        unset($cate_sql);
        $sp_category = array();
        if (is_array($result_category))
        {
            foreach ($result_category as  $value)
            {
                $sp_category[] = $value['nns_sp_category_id'];//获取绑定栏目
            }
        }
        $category_id = $sp_config['import_csp_id'] . $program_info['nns_category_id'];
        if(!empty($sp_category) && isset($sp_category[0]))
        {
            $category_id = $sp_config['import_csp_id'] . $sp_category[0];
        }

        $obj_cate_id = $sp_config['import_csp_id'] . i_object_guid(26);
        $xml_str .= '<Mapping ParentType="Category" ParentID="'.$category_id.'" ElementType="Program" ElementID="'.$index_import_id.'" ObjectID="'.$obj_cate_id.'" Action="' . $action . '">';
        $xml_str .= '</Mapping>';
        $xml_str .= '</Mappings>';
        $xml_str .= '</ADI>';
        $guid = np_guid_rand();
        $file_name = 'series_' . $program_id . '_' . $guid . '.xml';
        $c2_info = array(
            'nns_task_type' => 'Series',
            'nns_task_id' => $program_id,
            'nns_task_name' => isset($program_info['nns_task_name']) ? $program_info['nns_task_name'] : null,
            'nns_action' => $action,
            'nns_url' => $file_name,
            'nns_content' => $xml_str,
            'nns_desc' => 'Series,' . $action,
        );
        //执行注入cdn
        return self::execute_c2($c2_info, $sp_id);
    }

    /**
     * @description:组装上下线的剧集信息
     * @author:xinxin.deng
     * @date: 2018/1/10 11:34
     * @param $program_info
     * @param $action
     * @param $program_id
     * @return string
     */
    static public function build_program_line($program_info, $action, $program_id)
    {
        $sequence = '';
        if ($program_info['nns_series_flag'])
        {//连续剧
            $sequence = $program_info['nns_index'] + 1;
        }
        $xml_str = '<Object ElementType="Program" ContentID="' . $program_id . '" Action="' . $action . '">';
        $xml_str .= '<Property Name="Name">' . htmlspecialchars($program_info['nns_name'], ENT_QUOTES) . '</Property>';
        $xml_str .= '<Property Name="FileURL"></Property>';//切片文件
        $xml_str .= '<Property Name="SeriesFlag">' . $program_info['nns_series_flag'] . '</Property>';//0: 普通VOD 1: 连续剧剧集
        $xml_str .= '<Property Name="SortName">' . $sequence . '</Property>';//索引名称供界面排序 剧集时必填
        $xml_str .= '<Property Name="CPContentID">' . $program_info["nns_cp_id"] . '</Property>';//CP对于该节目的标识
        $xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
        $xml_str .= '<Property Name="CpContentID">' . $program_info["nns_cp_id"] . '</Property>';//CP内部对于该节目的标识
        $xml_str .= '<Property Name="OriginalName"></Property>';//原名
        $xml_str .= '<Property Name="SearchName"></Property>';//搜索名称供界面搜索
        $xml_str .= '<Property Name="ActorDisplay"></Property>';//演员列表,多个以逗号分隔
        $xml_str .= '<Property Name="WriterDisplay"></Property>';//作者列表
        $xml_str .= '<Property Name="OriginalCountry"></Property>';//国家地区
        $xml_str .= '<Property Name="Language"></Property>';//语言
        $xml_str .= '<Property Name="ReleaseYear"></Property>';//上映年份(YYYY)
        $xml_str .= '<Property Name="OrgAirDate"></Property>';//首播日期(YYYYMMDD)
        $xml_str .= '<Property Name="LicensingWindowStart">'. date('YmdHis').'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
        $xml_str .= '<Property Name="LicensingWindowEnd">'. date('YmdHis',time()+ 3*365*24*60*60).'</Property>';//有效结束时间(YYYYMMDDHH24MiSS)
        $xml_str .= '<Property Name="DisplayAsNew"></Property>';//新到天数
        $xml_str .= '<Property Name="DisplayAsLastChance">300</Property>';//剩余天数
        $xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护    1:有拷贝保护
        $xml_str .= '<Property Name="Description"></Property>';//节目描述
        $xml_str .= '<Property Name="PriceTaxIn"></Property>';//列表定价
        $xml_str .= '<Property Name="Status">1</Property>';//状态标志 0:失效 1:生效
        $xml_str .= '<Property Name="SourceType"></Property>';//1: VOD 5: Advertisement
        $xml_str .= '<Property Name="ContentProvider"></Property>';//节目提供商
        $xml_str .= '<Property Name="KeyWords"></Property>';//关键字 多个关键字之间使用分号分隔
        $xml_str .= '<Property Name="Tags"></Property>';//关联标签 多个标签之间使用分号分隔
        $xml_str .= '<Property Name="ViewPoint"></Property>';//看点
        $xml_str .= '<Property Name="StarLevel"></Property>';//推荐星级 从 1－10，数字越大推荐星 级越高，缺省为 6 ，为 3 颗星
        $xml_str .= '<Property Name="Rating"></Property>';//限制类别
        $xml_str .= '<Property Name="Awards"></Property>';//所含奖项
        $xml_str .= '<Property Name="Length"></Property>';//播放时长
        $xml_str .= '<Property Name="ProgramType"></Property>';//节目内容类型 字符串，表示内容类型，例如：电影，连续剧，新闻，体育…
        $xml_str .= '<Property Name="Reserve1"></Property>';//保留字段
        $xml_str .= '<Property Name="Reserve2"></Property>';//保留字段
        $xml_str .= '<Property Name="Reserve3"></Property>';//保留字段
        $xml_str .= '<Property Name="Reserve4"></Property>';//保留字段
        $xml_str .= '<Property Name="Reserve5"></Property>';//保留字段s
        $xml_str .= '<Property Name="UniContentId"></Property>';//所属全局内容一标识
        $xml_str .= '</Object>';

        return $xml_str;
    }

	/**
	 * 没有处理的指令，再次重发
	 */
	static public function resend_c2_again($sp_id)
	{
		$db = nn_get_db(NL_DB_READ);
		/************超时没返回重发************/
		$time_out = 3600;
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='$sp_id' and nns_again=0 and nns_create_time < NOW() - INTERVAL ".$time_out." SECOND  and nns_notify_result is null  order by nns_create_time asc  limit 90";
		$all = nl_db_get_all($sql,$db);	
		if(is_array($all)) {
			foreach($all as $item0){
				self::execute_c2_again($item0['nns_id'],$sp_id);
			}			
		}
		
		/************以下为失败重发************/
		//连续剧
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='$sp_id' and    (nns_notify_result='-1' and (nns_notify_result_url=''  or nns_notify_content like '%Entity queue is full%') or nns_result like '%[-1]soap info is full%') and nns_again=0 order by nns_again asc,nns_create_time asc  limit 90";
		$all = nl_db_get_all($sql,$db);
		if(is_array($all)) {
			foreach($all as $item0){
				self::execute_c2_again($item0['nns_id'],$sp_id);
			}			
		}
	}
	static public function execute_c2_again($nns_id,$sp_id)
	{
		$db = nn_get_db(NL_DB_READ);
        $db_w = nn_get_db(NL_DB_WRITE);
		$sql = "select * from nns_mgtvbk_c2_log where nns_id='$nns_id'";
		$c2_info = nl_db_get_one($sql,$db);
		$sql = "update nns_mgtvbk_c2_log set nns_again=1 ,nns_notify_result='-1',nns_modify_time=now() where nns_id='".$nns_id."'";
		nl_execute_by_db($sql,$db_w);	
		if($c2_info['nns_task_id'])
		{
			content_task_model::vod($c2_info['nns_task_id'],null,$sp_id);
		}	
		return true;
	}
	/**
	 * 执行C2注入命令
	 * @param $c2_info array(
	 * 			'c2_id'
	 * 			'file_name'
	 * 			'xml_content'
	 * )
	 */
	static public function execute_c2($c2_info,$sp_id)
	{
		$db = nn_get_db(NL_DB_WRITE);
		$db_r = nn_get_db(NL_DB_READ);
		$sp_config = sp_model::get_sp_config($sp_id);
		include_once dirname(dirname(dirname(dirname(__FILE__)))).'/import_service/'.$sp_id.'/'.$sp_id.'_cdn_client.php';
		$c2_id = np_guid_rand();
		if(!self::exists_c2_commond($c2_info,$sp_id))
		{
			$sub_path = date('Y-m-d');
			$file = $c2_info['nns_url'];
			$c2_info['nns_url'] = $sub_path.'/'.$file;
			$xml_str = $c2_info['nns_content'];

			$file_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$sp_id.'/inject_xml/cntv_me_xml/'.$sub_path.'/';

			if(!is_dir($file_path))
			{
				mkdir($file_path,0777,true);
			}
			$file_path .= $file;

			file_put_contents($file_path,$xml_str);
			$md5 = md5($xml_str);
			$CmdFileURL = C2_FTP . '/' .$c2_info['nns_url'];	
			$c2_info['nns_id'] = $c2_id;

			try {
                $exist_result = null;
				//CDN单日志模式开启
				if($sp_config['cdn_single_log_mode']=='0')
				{
					$exist_result = self::check_task_log_is_exist($c2_info['nns_task_id'],$c2_info['nns_action'],$db_r);
					if(is_array($exist_result) && !empty($exist_result))
					{
						$c2_id = $exist_result[0]['nns_id'];
						$c2_info['nns_id'] = $c2_id;
						$c2_info['nns_notify_fail_reason'] = '';
						$c2_info['nns_cdn_send_time'] = $exist_result[0]['nns_cdn_send_time']+1;
						$c2_info['nns_create_time'] = $exist_result[0]['nns_create_time'];
						$c2_info['nns_notify_content'] = "";
						self::update_c2_log($c2_info,$sp_id);
						self::update_c2_log_is_null(array('nns_result','nns_notify_result_url','nns_notify_result'),array('nns_id'=>$c2_info['nns_id']),$db);
						nn_log::write_log_message(LOG_MODEL_CDN, 'CDN单日志C2_LOG信息'.var_export($c2_info,true), ORG_ID);
					}
				}
				np_runtime_ex($c2_id,false);
				$result = call_user_func_array(array($sp_id.'_cdn_client', 'ContentMngReq'), array($c2_id, $CmdFileURL,$md5));
				$c2_info['nns_result'] = '['.$result->ResultCode.']';			
				$bool = false;
				if($result->ResultCode != 0 )
				{
					$c2_info['nns_result'] = '[-1]'.$result->ErrorDescription;
					//$c2_info['nns_notify_result'] = -1;
					$bool = true;
				}
				DEBUG && i_write_log_core('---------execute soap time----------'.np_runtime_ex($c2_id,true),'soap');
				DEBUG && i_write_log_core('---------execute soap time----------'.var_export($result,true),'soap');
				if(is_array($exist_result) && !empty($exist_result))
				{
//                    self::update_c2_state('5',$c2_info['nns_task_id'],$db);
					self::update_c2_log($c2_info,$sp_id);
				}
				else
				{
					self::save_c2_log($c2_info,$sp_id);
				}
				if($bool)
				{
					return false;
				}
				return true;
			}
			catch (Exception $e)
			{
				DEBUG && i_write_log_core(var_export($e,true),$sp_id.'/c2');
				$c2_info['nns_result'] = '[-1]网络错误';
				//$c2_info['nns_notify_result'] = -1;
				self::save_c2_log($c2_info,$sp_id);
				return false;
			}		
		}
		return false;
		
	}	
	static public function exists_c2_commond($c2_info,$sp_id)
	{
	    return false;
		set_time_limit(0);
    	$db_r = nn_get_db(NL_DB_READ);
    	$nns_org_id = $sp_id;
    	$nns_task_type = $c2_info['nns_task_type'];
    	$nns_task_id = $c2_info['nns_task_id'];
    	$nns_action = $c2_info['nns_action'];	
		if(empty($nns_task_id)) 
		{
			return false;
		}		
		usleep(5000);
		//检查一小时前 是否相同的任务未返回结果
    	$sql = "select 1 from nns_mgtvbk_c2_log where nns_org_id='$nns_org_id' and nns_task_type='$nns_task_type' and nns_task_id='$nns_task_id' and nns_action='$nns_action' and nns_notify_result is null and nns_create_time > NOW() - INTERVAL 3600 SECOND";
    	$data = nl_db_get_all($sql,$db_r);	
    	if(is_array($data) && count($data) > 0)
    	{
    		return true;
    	}
    	return false;
    }
	/**
	 * 保存C2命令日志
	 * $c2_log array(
	 * 			'nns_id',
	 * 			'nns_type',
	 * 			'nns_org_id',
	 * 			'nns_video_id',
	 * 			'nns_video_type',
	 * 			'nns_video_index_id',
	 * 			'nns_media_id',
	 * 			'nns_url',
	 * 			'nns_content',
	 * 			'nns_result',
	 * 			'nns_desc',
	 * 			'nns_create_time'
	 * )
	 */
	static public function save_c2_log($c2_log,$sp_id)
	{
		$db = nn_get_db(NL_DB_WRITE);
		$c2_log['nns_type'] = 'std';
		$c2_log['nns_org_id'] = $sp_id;
		$dt = date('Y-m-d H:i:s');
		$c2_log['nns_create_time'] = $dt;
		$c2_log['nns_send_time'] = $dt;
		return nl_db_insert($db,'nns_mgtvbk_c2_log',$c2_log);
	}
	/**
	 * C2通知命令日志
	 * $c2_notify array(
	 * 'nns_id',
	 * 'nns_notify_result_url',
	 * 'nns_notify_result',
	 * )
	 */
	static public function save_c2_notify_child($c2_notify)
	{		
		$db = nn_get_db(NL_DB_WRITE);
		$db_r = nn_get_db(NL_DB_READ);
		$dt = date('Y-m-d H:i:s');
		$wh_content ="";
		if($c2_notify['nns_notify_result'] != '-1')
		{
			$wh_content = "nns_content='',";
		}
		$sql = "update nns_mgtvbk_c2_log set " .
				"nns_notify_result_url='".$c2_notify['nns_notify_result_url']."' ," .$wh_content.
				"nns_notify_result='".$c2_notify['nns_notify_result']."', nns_notify_time='".$dt."'," .
				"nns_modify_time='".$dt."' " .
				"where nns_id='".$c2_notify['nns_id']."'";
		nl_execute_by_db($sql,$db);
	
		$sql = "select * from nns_mgtvbk_c2_log where nns_id='".$c2_notify['nns_id']."'";
		$c2_info = nl_db_get_one($sql,$db_r);
		$sp_config = sp_model::get_sp_config($c2_info['nns_org_id']);
		//如果回馈的消息是重发的消息
		if($sp_config['cdn_single_log_mode'] != '0')
		{
			if($c2_info == false || $c2_info['nns_again'] >= 1)
			{
				return false;
			}
		}
		DEBUG && i_write_log_core('---------save_c2_notify----------',$c2_info['nns_org_id'].'/c2notify');
		if($c2_info['nns_task_type'] == 'Series' || $c2_info['nns_task_type'] == 'Program' || $c2_info['nns_task_type'] == 'Movie')
		{
			if($c2_notify['nns_notify_result'] == '0')
			{				
				$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
				if($c2_info['nns_task_type'] == 'Series' && $c2_info['nns_action']=='DELETE' && $sp_config['video_destroy']['priority']=='1')
				{
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=99 where nns_id='".$c2_info['nns_task_id']."'";
				}
				if($c2_info['nns_task_type'] == 'Program' && $c2_info['nns_action']=='DELETE' && $sp_config['index_destroy']['priority']=='1')
				{
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=99 where nns_id='".$c2_info['nns_task_id']."'";
				}
				if($c2_info['nns_task_type'] == 'Movie' && $c2_info['nns_action']=='DELETE' && $sp_config['media_destroy']['priority']=='1')
				{
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=99 where nns_id='".$c2_info['nns_task_id']."'";
				}
				//是否需要异步获取播放穿				
				$cdn_query_mediaurl_bool = false;
				if(isset($sp_config['cdn_query_mediaurl']) && (int)$sp_config['cdn_query_mediaurl'] === 1)
				{
					$cdn_query_mediaurl_bool = true;
				}				
				if($cdn_query_mediaurl_bool && $c2_info['nns_task_type']=='Movie')
				{
					
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=6,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
					$sql_info = "select * from nns_mgtvbk_c2_task where nns_id='{$c2_info['nns_task_id']}'";
					$c2__taskinfo = nl_db_get_one($sql_info,$db_r);
					
					if(is_array($c2__taskinfo))
					{
						if($c2__taskinfo['nns_status'] == '0')
						{
							$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
						}
					}				
					if($c2_info['nns_action'] == 'DELETE')
					{
						$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
					}
				}
			}
			else 
			{
				$sql_update = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目					
				if($c2_info['nns_task_type'] == 'Series' && $c2_info['nns_action']=='DELETE' && $sp_config['video_destroy']['priority']=='1')
				{
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time=now(),nns_epg_status=99 where nns_id='".$c2_info['nns_task_id']."'";
				}
				if($c2_info['nns_task_type'] == 'Program' && $c2_info['nns_action']=='DELETE' && $sp_config['index_destroy']['priority']=='1')
				{
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time=now(),nns_epg_status=99 where nns_id='".$c2_info['nns_task_id']."'";
				}
				if($c2_info['nns_task_type'] == 'Movie' && $c2_info['nns_action']=='DELETE' && $sp_config['media_destroy']['priority']=='1')
				{
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time=now(),nns_epg_status=99 where nns_id='".$c2_info['nns_task_id']."'";
				}
			}
			nl_execute_by_db($sql_update,$db);	
		}
		//如果是片源且开启了播控切片
		if($c2_info['nns_task_type'] == 'Movie' && (int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
		{			
			$sql_c2_task = nl_db_get_one("select * from  nns_mgtvbk_c2_task  where nns_id='".$c2_info['nns_task_id']."'", $db);
			if($c2_info['nns_action']=='DELETE')
			{
				if($c2_notify['nns_notify_result'] != '0')
				{
					$nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_FAIL;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_FAIL];		
				}
				else
				{
					$nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_SUCC;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_SUCC];					
				}
			}
			else
			{
				if($c2_notify['nns_notify_result'] != '0')
				{
					$nns_state = clip_task_model::TASK_C_STATE_C2_FAIL;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_FAIL];	
				}
				else
				{
					$nns_state = clip_task_model::TASK_C_STATE_C2_SUCC;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_SUCC];					
				}
			}
				
			//更改切片状态
			$dt = date('Y-m-d H:i:s');
			$set_state = array(
				'nns_state' => $nns_state,
				'nns_desc' => $nns_desc,
				'nns_modify_time'=>$dt,
			);
			clip_task_model::update_task($sql_c2_task['nns_clip_task_id'], $set_state);
			//任务日志	
			$task_log = array(
				'nns_task_id' => $sql_c2_task['nns_clip_task_id'],
				'nns_state' => $nns_state,
				'nns_desc' => $nns_desc,
			);	
			clip_task_model::add_task_log($task_log);
		}
		//通知列队
		if($c2_notify['nns_notify_result'] == '0')
		{
			include_once dirname(dirname(dirname(__FILE__))).'/models/queue_task_model.php';
			$queue_task_model = new queue_task_model();
			$queue_task_model->q_report_task($c2_info['nns_task_id']);
			$queue_task_model = null;
		}
		
		//下载结果
		if(!empty($c2_notify['nns_notify_result_url']) && $c2_notify['nns_notify_result_url']!=='NULL')
		{
			$sql_info = "select * from nns_mgtvbk_c2_task where nns_id='{$c2_info['nns_task_id']}'";
			$c2_taskinfo = nl_db_get_one($sql_info,$db_r);
			$url_arr = parse_url($c2_notify['nns_notify_result_url']);
			$port = isset($url_arr["port"])?$url_arr["port"]:21;
			include_once NPDIR . '/np_ftp.php';
			//include_once NPDIR . '/np_xml2array.class.php';
			$ftp1=new nns_ftp($url_arr['host'],$url_arr["user"],$url_arr["pass"],$port);
			$ftpcon1=$ftp1->connect();
            if (empty($ftpcon1))
            {
            	DEBUG && i_write_log_core('---------FTP链接失败----------',$c2_info['nns_org_id'].'/c2notify');
				$sql_log = "update nns_mgtvbk_c2_log set nns_notify_result='-1',nns_notify_fail_reason='FTP链接失败' where nns_id='".$c2_notify['nns_id']."'";
				nl_execute_by_db($sql_log,$db);
				//添加失败次数
				$c2_taskinfo['nns_cdn_fail_time'] = $c2_taskinfo['nns_cdn_fail_time']+1;
				$sql_c2 = "update nns_mgtvbk_c2_task set nns_cdn_fail_time=".$c2_taskinfo['nns_cdn_fail_time']." where nns_id='".$c2_info['nns_task_id']."'";
				nl_execute_by_db($sql_c2,$db);
				if($sp_config['cdn_fail_retry_mode'] == '0' && $c2_taskinfo['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time'])
				{
					$sql_c2 = "update nns_mgtvbk_c2_task set nns_status='1' where nns_id='".$c2_info['nns_task_id']."'";
					$result = nl_execute_by_db($sql_c2,$db);
					if(!$result)
					{
						DEBUG && i_write_log_core('---------FTP链接失败后修改C2状态失败----------',$c2_info['nns_org_id'].'/c2notify');
					}
				}
				return FALSE;
            }
            $notify_save_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$c2_info['nns_org_id'].'/notify'.$url_arr["path"];
            $path_parts = pathinfo($notify_save_path);
             if (!is_dir($path_parts['dirname']))
             {
                 mkdir($path_parts['dirname'], 0777, true);
             }            
            $rs = $ftp1->get(ltrim($url_arr["path"],'/'),$notify_save_path);
            if($rs == false)
            {
            	DEBUG && i_write_log_core('---------下载 notify 失败----------',$c2_info['nns_org_id'].'/c2notify');
				$sql_log = "update nns_mgtvbk_c2_log set nns_notify_result='-1',nns_notify_fail_reason='下载notify失败' where nns_id='".$c2_notify['nns_id']."'";
				nl_execute_by_db($sql_log,$db);
				//添加失败次数
				$c2_taskinfo['nns_cdn_fail_time'] = $c2_taskinfo['nns_cdn_fail_time']+1;
				$sql_c2 = "update nns_mgtvbk_c2_task set nns_cdn_fail_time=".$c2_taskinfo['nns_cdn_fail_time']." where nns_id='".$c2_info['nns_task_id']."'";
				nl_execute_by_db($sql_c2,$db);
				if($sp_config['cdn_fail_retry_mode'] == '0' && $c2_taskinfo['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time'])
				{
					$sql_c2 = "update nns_mgtvbk_c2_task set nns_status='1' where nns_id='".$c2_info['nns_task_id']."'";
					$result = nl_execute_by_db($sql_c2,$db);
					if(!$result)
					{
						DEBUG && i_write_log_core('---------下载 notify 失败后修改C2状态失败----------',$c2_info['nns_org_id'].'/c2notify');
					}
				}
				return FALSE;
            }
            //获取下载的内容 进行保存
            if(!file_exists($notify_save_path))
            {
            	DEBUG && i_write_log_core('---------文件不存在----------',$c2_info['nns_org_id'].'/c2notify');
				$sql_log = "update nns_mgtvbk_c2_log set nns_notify_result='-1',nns_notify_fail_reason='下载通知文件保存失败' where nns_id='".$c2_notify['nns_id']."'";
				nl_execute_by_db($sql_log,$db);
				//添加失败次数
				$c2_taskinfo['nns_cdn_fail_time'] = $c2_taskinfo['nns_cdn_fail_time']+1;
				$sql_c2 = "update nns_mgtvbk_c2_task set nns_cdn_fail_time=".$c2_taskinfo['nns_cdn_fail_time']." where nns_id='".$c2_info['nns_task_id']."'";
				nl_execute_by_db($sql_c2,$db);
				if($sp_config['cdn_fail_retry_mode'] == '0' && $c2_taskinfo['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time'])
				{
					$sql_c2 = "update nns_mgtvbk_c2_task set nns_status='1' where nns_id='".$c2_info['nns_task_id']."'";
					$result = nl_execute_by_db($sql_c2,$db);
					if(!$result)
					{
						DEBUG && i_write_log_core('---------下载下载通知文件保存失败后修改C2状态失败----------',$c2_info['nns_org_id'].'/c2notify');
					}
				}
            	return false;
            }
            $content = @file_get_contents($notify_save_path);

            if($c2_info['nns_task_type'] == 'Movie' && $c2_info['nns_action'] !== 'DELETE')
            {
	            //如果是movie时解析XML，保存至C2_task中
            	$dom = new DOMDocument('1.0', 'utf-8');
				$dom->loadXML($content);
				$xpath = new DOMXPath($dom);
				$entries = $xpath -> query('/ADI/Reply/Resultinfo/Property');
				$notify_list = array();
				foreach ($entries as $item)
				{
					foreach ($item->attributes as $val)
					{
						$notify_list[$val->nodeValue] = $item->nodeValue;
					} 
				}
				DEBUG && i_write_log_core('解析反馈的XML内容为:'.var_export($notify_list,true),$c2_info['nns_org_id'].'/c2notify');
				if($notify_list['ResultCode'] == '0')
				{
					DEBUG && i_write_log_core('-----------播放地址入库-------------',$c2_info['nns_org_id'].'/c2notify');
					$ex_url = $notify_list['PlayUrl'];
					DEBUG && i_write_log_core('PlayUrl为:'.var_export($ex_url,true),$c2_info['nns_org_id'].'/c2notify');
					$sql_c2_url = "update nns_mgtvbk_c2_task set nns_ex_url='{$ex_url}',nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";
					$result = nl_execute_by_db($sql_c2_url,$db);
					if(!$result)
					{
						DEBUG && i_write_log_core('-----------播放地址入库失败-------------',$c2_info['nns_org_id'].'/c2notify');
						$sql_log = "update nns_mgtvbk_c2_log set nns_notify_result='-1',nns_notify_fail_reason='播放地址入库失败' where nns_id='".$c2_notify['nns_id']."'";
						nl_execute_by_db($sql_log,$db);
						//添加失败次数
						$c2_taskinfo['nns_cdn_fail_time'] = $c2_taskinfo['nns_cdn_fail_time']+1;
						$sql_c2 = "update nns_mgtvbk_c2_task set nns_cdn_fail_time=".$c2_taskinfo['nns_cdn_fail_time']." where nns_id='".$c2_info['nns_task_id']."'";
						nl_execute_by_db($sql_c2,$db);
						if($sp_config['cdn_fail_retry_mode'] == '0' && $c2_taskinfo['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time'])
						{
							$sql_c2 = "update nns_mgtvbk_c2_task set nns_status='1' where nns_id='" . $c2_info['nns_task_id'] . "'";
							$result = nl_execute_by_db($sql_c2, $db);
							if (!$result) {
								DEBUG && i_write_log_core('---------播放地址入库失败后修改C2状态失败----------', $c2_info['nns_org_id'] . '/c2notify');
							}
						}
						return false;
					}
				}
				else
				{
					DEBUG && i_write_log_core('-----------注入发生错误，播放地址未入库-------------',$c2_info['nns_org_id'].'/c2notify');
					$sql_log = "update nns_mgtvbk_c2_log set nns_notify_result='-1',nns_notify_fail_reason='注入发生错误，播放地址未入库' where nns_id='".$c2_notify['nns_id']."'";
					nl_execute_by_db($sql_log,$db);
					//添加失败次数
					$c2_taskinfo['nns_cdn_fail_time'] = $c2_taskinfo['nns_cdn_fail_time']+1;
					$sql_c2 = "update nns_mgtvbk_c2_task set nns_cdn_fail_time=".$c2_taskinfo['nns_cdn_fail_time']." where nns_id='".$c2_info['nns_task_id']."'";
					nl_execute_by_db($sql_c2,$db);
					if($sp_config['cdn_fail_retry_mode'] == '0' && $c2_taskinfo['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time'])
					{
						$sql_c2 = "update nns_mgtvbk_c2_task set nns_status='1' where nns_id='" . $c2_info['nns_task_id'] . "'";
						$result = nl_execute_by_db($sql_c2, $db);
						if (!$result) {
							DEBUG && i_write_log_core('---------注入发生错误，播放地址未入库后修改C2状态失败----------', $c2_info['nns_org_id'] . '/c2notify');
						}
					}
					return false;
				}
            }
			if($c2_info['nns_task_type'] == 'Movie' && $c2_info['nns_action'] == 'DELETE')
			{
				$dom = new DOMDocument('1.0', 'utf-8');
				$dom->loadXML($content);
				$xpath = new DOMXPath($dom);
				$entries = $xpath -> query('/ADI/Reply/Resultinfo/Property');
				$notify_list = array();
				foreach ($entries as $item)
				{
					foreach ($item->attributes as $val)
					{
						$notify_list[$val->nodeValue] = $item->nodeValue;
					}
				}
				DEBUG && i_write_log_core('解析反馈的XML内容为:'.var_export($notify_list,true),$c2_info['nns_org_id'].'/c2notify');
				if($notify_list['ResultCode'] == '0')
				{
					DEBUG && i_write_log_core('-----------Movie删除成功-------------',$c2_info['nns_org_id'].'/c2notify');
					$sql_log = "update nns_mgtvbk_c2_log set nns_notify_result='0',nns_notify_fail_reason='".$notify_list['Result']."' where nns_id='".$c2_notify['nns_id']."'";
					$result = nl_execute_by_db($sql_log,$db);
					if(!$result)
					{
						DEBUG && i_write_log_core('---------Movie删除成功后修改C2_log状态失败----------',$c2_info['nns_org_id'].'/c2notify');
						return false;
					}
				}
				else
				{
					DEBUG && i_write_log_core('-----------Movie删除失败-------------',$c2_info['nns_org_id'].'/c2notify');
					$sql_log = "update nns_mgtvbk_c2_log set nns_notify_result='-1',nns_notify_fail_reason='".$notify_list['Result']."' where nns_id='".$c2_notify['nns_id']."'";
					$result = nl_execute_by_db($sql_log,$db);
					if(!$result)
					{
						DEBUG && i_write_log_core('---------Movie删除失败后修改C2_log状态失败----------',$c2_info['nns_org_id'].'/c2notify');
					}
					return false;
				}
			}
//            $c2_update_sql = "update nns_mgtvbk_c2_log set nns_notify_content='{$content}' where nns_id='{$c2_notify['nns_id']}'";
//            nl_execute_by_db($c2_update_sql,$db);
		}	
		return true;
	}		
	static  public function check_ftp_file($url)
	{
		$url_arr = parse_url($url);
		$port = isset($url_arr["port"]) ? $url_arr["port"] : 21;
		$time = 10;
		$connect_no = ftp_connect($url_arr['host'],$port,$time);
		if ($connect_no === FALSE) return FALSE;
		
		@ftp_login(
			$connect_no,
			$url_arr["user"],
			$url_arr["pass"]
		);
		//吉林联通要开启被动模式
		@ftp_pasv($connect_no,true);
		$contents = @ftp_nlist($connect_no, $url_arr['path']);
		if($contents===false)
		{
			return FALSE;
		}
		else
		{
			if(empty($contents))
			{
				return FALSE;
			}
			return true;
		}
	}
	/**
	 * 根据图片地址获取图片ID
	 * @param $img 图片地址
	 */
	static public function get_image_id($img)
	{
		if(!empty($img))
		{
			$img_arr = explode('+', $img);
			$img_pic = end($img_arr);
			if(!empty($img_pic))
			{
				$img_arr = explode('.', $img_pic);
				return $img_arr[0];
			}
		}
	}

	/**
	 * 检测该任务是否执行过
	 * @param $task_id
	 * @param $db
	 * @return bool
	 */
	static public function check_task_log_is_exist($task_id,$action,$db)
	{
		$time = date('Y-m-d');
		$sql = "select * from nns_mgtvbk_c2_log where nns_task_id='".$task_id."' and nns_action='".$action."' order by nns_create_time desc limit 1";
		return nl_query_by_db($sql,$db);
	}

	/**
	 * 更新CDN日志
	 * @param $c2_log
	 * @param $sp_id
	 * @return bool
	 */
	static public function update_c2_log($c2_log,$sp_id)
	{
		$db = nn_get_db(NL_DB_WRITE);
		$c2_log['nns_type'] = 'std';
		$c2_log['nns_org_id'] = $sp_id;
		$dt = date('Y-m-d H:i:s');
		$c2_log['nns_create_time'] = isset($c2_log['nns_create_time']) && !empty($c2_log['nns_create_time']) ? $c2_log['nns_create_time'] : $dt;
		$c2_log['nns_send_time'] = $dt;
		return nl_db_update($db,'nns_mgtvbk_c2_log',$c2_log,array('nns_id'=>$c2_log['nns_id']));
	}

	/**制空CDN日志字段
	 * @param $is_null_field
	 * @param null $where
	 * @param $db
	 * @return bool
	 */
	static public function update_c2_log_is_null($is_null_field,$where=null,$db)
	{
		if(is_array($is_null_field) && !empty($is_null_field))
		{
			foreach($is_null_field as $val)
			{
				$filed[] = $val."= null";
			}
		}
		else
		{
			return true;
		}
		$str = rtrim(implode(',',$filed),',');
		$wh = array();
		if (is_array($where)) {
			foreach ($where as $k => $v) {
				if (strpos($k, 'nns_') === FALSE)
					$k = 'nns_' . $k;
				$wh[] = "$k='$v'";
			}
			!empty($wh) && $where = implode(' and ', $wh);
		}
		if (is_string($where) && $where)
			$where = "where $where";
		$sql = "update nns_mgtvbk_c2_log set $str $where";
		return nl_execute_by_db($sql,$db);
	}


    /**
     * 更新CDN状态
     * @param $state
     * @param $task_id
     * @param $db
     * @return bool
     */
    static public function update_c2_state($state,$task_id,$db)
    {
        $sql = "update nns_mgtvbk_c2_task set nns_status = $state where nns_id ='".$task_id."'";
        return nl_execute_by_db($sql,$db);
    }
}
